package intranet.client;
import intranet.client.Session;

import java.util.Date;
import java.util.HashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.i18n.client.DateTimeFormat;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import com.google.gwt.user.client.ui.DecoratedStackPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLTable.RowFormatter;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;

import com.google.gwt.user.client.ui.VerticalPanel;


/**
 * @author Robin TROADEC
 */
public class TemplatesTab extends VerticalPanel
{
	private static final String SERVER_ERROR = "An error occurred while "
		+ "attempting to contact the server. Please check your network "
		+ "connection and try again.";

	private final TemplatesTabFuncAsync templatesFunc = GWT
		.create(TemplatesTabFunc.class);
	private final DataBaseServiceAsync dataService = GWT
	.create(DataBaseService.class);
	
	protected HorizontalPanel creaPanel,visuPanel;
	protected VerticalPanel centrPanel;
	protected VerticalPanel insideCreaPanel;
	protected FlexTable flexTable;
	protected ScrollPanel scrollPan;
	protected Session s;
	protected DecoratedStackPanel func;
	
	protected RichTextArea textHtml;
	protected RichTextToolbar toolbar;
	protected HashMap<String,String[]> myValue;
	protected RowFormatter row;
	protected HashMap<String,String> myButton;
	protected HashMap<String,String> myDel;
	protected ClickHandler cl,clDel;
	protected Frame fr;

	//Menu
	protected MenuItem menuTemplate, menuCrea , menuVisu,menuSave, menuExport;
	protected Command cmdTempl,cmdCrea,cmdVisu,cmdSave,cmd2pdf;
	protected MenuBar menu;
	
	//Boite de dialog
	protected DialogBox dialogSave,dialogExp;
	protected VerticalPanel vpSave,vpExp ;
	protected PushButton validSave,validExp;
	protected PushButton delSave,delExp;
	protected ValidTextBox frameNameSave,frameNameExp;
	protected ListBox visibilitySave,visibilityExp,courseExp;
	
	
	protected VerticalPanel vp1;
	protected Tree treePerso,treeGen;
	
	
	/**
	 * Constructeur d'un panel de gestion des template
	 * @param sees - La session courante
	 */
	public TemplatesTab(Session sess)
	{
		s=sess;
		
		
		//Creation de la menubar
		createMenuBar();
		fr = null;
		
		
		//Hashmap des valeurs et des event sur les boutons
		myButton=new HashMap<String, String>();
		myValue=new HashMap<String, String[]>();
		myDel = new HashMap<String, String>();
		centrPanel = new VerticalPanel();
		centrPanel.setHorizontalAlignment(ALIGN_CENTER);
		
		//ClickHandler de chargement de templates
		cl = new ClickHandler()
		{			
			public void onClick(ClickEvent event)
			{
				
				PushButton tpB = (PushButton)event.getSource();
				templatesFunc.load(myButton.get(tpB.getTitle()), new AsyncCallback<String>()
				{
					public void onFailure(Throwable caught)
					{
						Window.alert("Template load : "+SERVER_ERROR);
					}

					public void onSuccess(String result)
					{
						centrPanel.clear();
						centrPanel.add(creaPanel);
						textHtml.setHTML(result);
						if (!result.equals(""))
						{
							menuVisu.setVisible(true);
							menuSave.setVisible(true);
							menuExport.setVisible(true);
						}
					}
				});
			}
		};
		
		//ClickHandler de suppression de templates
		clDel = new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{				
				final PushButton tpB = (PushButton)event.getSource();
				templatesFunc.delete(myDel.get(tpB.getTitle()).split(":")[1], new AsyncCallback<Boolean>()
				{
					public void onFailure(Throwable caught)
					{
						Window.alert("Template delete : "+SERVER_ERROR);
					}

					public void onSuccess(Boolean result)
					{
						if (result)
						{	
							String r = "Delete from teacher_template where template_id='"+myDel.get(tpB.getTitle()).split(":")[0]+"'";
							dataService.delete(r, new AsyncCallback<Integer>()
							{
								public void onSuccess(Integer result)
								{
									if (result>0)
									{
										centrPanel.clear();
										createListe();
										centrPanel.add(scrollPan);
									}
								}
								
								public void onFailure(Throwable caught)
								{
									Window.alert("Data delete : "+SERVER_ERROR);
								}
							});
						}
						else
						{
							Window.alert("Erreur lors de la supression");
						}
					}
				});
			}	
		};
		
		
		//recuperation des information du professeur courant
        String sessionReq = "Select teacher_name,teacher_firstname,teacher_email,teacher_tel from teacher where teacher_login='"+s.get("teacher_login")+"'";
        dataService.select(sessionReq, new AsyncCallback<HashMap<String,String[]>>()
		{
			public void onFailure(Throwable caught)
			{
				Window.alert("Login : "+SERVER_ERROR);
			}

			@SuppressWarnings("unchecked")
			public void onSuccess(HashMap<String, String[]> result)
			{	
				myValue=(HashMap<String, String[]>) result.clone();
			}
		});

        
        
		//Creation panel qui liste les templates
		flexTable = new FlexTable();
		flexTable.setStyleName("overflow"); //Ajout de l'overflow pour faire apparaitre le scroll
		scrollPan = new ScrollPanel();
		
	   
		//Creation de la liste des templates
	    createListe();
	    scrollPan.add(flexTable);
	   
	   centrPanel.add(scrollPan);
		
		//Creation de creapanel - le panel de creation d'un template
		creaPanel = new HorizontalPanel();
		  
		//Initialisation du textarea complet
		initRichText();
		initStackPanel();
		
		creaPanel.add(insideCreaPanel);
		creaPanel.add(func);
		
		
		//creation de visualisation panel
		visuPanel = new HorizontalPanel();
		visuPanel.setHorizontalAlignment(ALIGN_CENTER);

        this.add(menu);
        this.add(centrPanel);
	}

	/**
	 * Fonction permettant de créer la liste des templates (Asynchrone)
	 */
	public void createListe()
	{
		flexTable.removeAllRows();
		 scrollPan.setSize(Window.getClientWidth()*16/20*19/20+"px",Window.getClientHeight()*9/10*17/20+"px");
		 flexTable.setWidth(Window.getClientWidth()*16/20*9/10+"px");
		
		String req = "select distinct teacher.teacher_login,teacher_name,teacher_firstname,teacher_template.template_id,template_name,template_path,template_date from teacher_template,teacher,template where teacher.teacher_login=teacher_template.teacher_login and template.template_id=teacher_template.template_id and (template.template_visibility='0' or teacher.teacher_login='"+s.get("teacher_login")+"')";
		dataService.select(req, new AsyncCallback<HashMap<String,String[]>>()
		{
			public void onSuccess(HashMap<String, String[]> result)
			{
				//Mise en forme de la table d'affichage
				flexTable.setText(0,1,"Nom");
				flexTable.getFlexCellFormatter().setHorizontalAlignment(0, 1, ALIGN_CENTER );
				flexTable.getFlexCellFormatter().addStyleName(0, 1, "backBlue");
				flexTable.setText(0,0,"Date");
				flexTable.getFlexCellFormatter().setHorizontalAlignment(0, 0, ALIGN_CENTER );
				flexTable.getFlexCellFormatter().addStyleName(0, 0, "backBlue");
				flexTable.setText(0,2,"Propriétaire");
				flexTable.getFlexCellFormatter().setHorizontalAlignment(0, 2, ALIGN_CENTER );
				flexTable.getFlexCellFormatter().addStyleName(0, 2, "backBlue");
				flexTable.setText(0,3,"Charger");
				flexTable.getFlexCellFormatter().setHorizontalAlignment(0, 3, ALIGN_CENTER );
				flexTable.getFlexCellFormatter().addStyleName(0, 3, "backBlue");
				flexTable.setText(0,4,"Suppr");
				flexTable.getFlexCellFormatter().setHorizontalAlignment(0, 4, ALIGN_CENTER );
				flexTable.getFlexCellFormatter().addStyleName(0, 4, "backBlue");
				
				//Si aucun templates
				if (result.get("template_name").length==0)
				{
					flexTable.getFlexCellFormatter().setColSpan(1, 0, 5);
					flexTable.getFlexCellFormatter().setHorizontalAlignment(1, 0, ALIGN_CENTER );
					flexTable.setText(1,0,"Auncun templates");
					
				}
				else
				{
					for (int i=0;i<result.get("template_name").length;i++)
					{		
						
						String dateS =DateTimeFormat.getFormat("dd/MM/yyyy HH:mm").format(new Date(new Long(result.get("template_date")[i])));
						flexTable.setText(i+1,1,result.get("template_name")[i]);
							flexTable.getFlexCellFormatter().setHorizontalAlignment(i+1, 1, ALIGN_CENTER );
						flexTable.setText(i+1,0,dateS.toString());
							flexTable.getFlexCellFormatter().setHorizontalAlignment(i+1, 0, ALIGN_CENTER );
						flexTable.setText(i+1,2,result.get("teacher_name")[i]+" "+result.get("teacher_firstname")[i]);
							flexTable.getFlexCellFormatter().setHorizontalAlignment(i+1, 2, ALIGN_CENTER );	
						
							/***Button load***/
						PushButton b = new PushButton(new Image("load.png"));
							b.setWidth("24px");
						b.setTitle(""+result.get("template_name")[i]);
						myButton.put(result.get("template_name")[i], result.get("template_path")[i]);
						b.addClickHandler(cl);
						flexTable.setWidget(i+1, 3, b);	
							flexTable.getFlexCellFormatter().setHorizontalAlignment(i+1, 3, ALIGN_CENTER );
						
							//Si possésseur du template
						if (result.get("teacher_login")[i].equals(s.get("teacher_login")))
						{
							/***Button delete***/
							b=new PushButton(new Image("delete.png"));
								b.setWidth("24px");
							b.setTitle(""+result.get("template_name")[i]);
							myDel.put(result.get("template_name")[i], result.get("template_id")[i]+":"+result.get("template_path")[i]);
							b.addClickHandler(clDel);
							flexTable.setWidget(i+1, 4, b);	
								flexTable.getFlexCellFormatter().setHorizontalAlignment(i+1,4, ALIGN_CENTER );
						}
					}	
				}
			}
			public void onFailure(Throwable caught)
			{
				Window.alert("Data List request : "+SERVER_ERROR);
			}
		});
	}
	
	/**
	 * Fonction appelée afin de sauvegarder un tempalate
	 */
	public void save()
	{
		//initialisation de la boite de dialog de sauvegarde
		initDialogSave();
		
		//Affichage panel recup info
		vpSave.clear();
		if (fr !=null)
			fr.setVisible(false);
		
		dialogSave.setGlassEnabled(true);
		dialogSave.setAnimationEnabled(true);
		dialogSave.setPopupPosition(600, 250);
		dialogSave.show();
		
		//Ajout de l'event sur le bouton valider
		validSave.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				final Date d = new Date();
				if (!frameNameSave.getText().equals(""))
				{
					templatesFunc.saveDoc(frameNameSave.getText(), textHtml.getHTML(),d.getTime(), s.get("teacher_login"), new AsyncCallback<String>()
					{
						public void onFailure(Throwable caught)
						{
							Window.alert("Document save : "+SERVER_ERROR);
						}
	
						public void onSuccess(String result)
						{
							String r="insert into template(template_name,template_path,template_date,template_visibility) " +
									"values ('"+frameNameSave.getText()+"','"+result+"','"+d.getTime()+"','"+visibilitySave.getValue((visibilitySave.getSelectedIndex()))+"')";
						
							dataService.insert(r, new AsyncCallback<Integer>()
							{
								public void onFailure(Throwable caught)
								{	
									Window.alert("Data insert : "+SERVER_ERROR);
								}
	
								public void onSuccess(Integer resulta)
								{
									String r= "insert into teacher_template values ('"+resulta+"','"+s.get("teacher_login")+"')";
									
									dataService.insert(r, new AsyncCallback<Integer>()
									{
										public void onFailure(
												Throwable caught)
										{
											Window.alert("Data insert : "+SERVER_ERROR);
										}
	
										public void onSuccess(Integer result)
										{
											dialogSave.clear();
											//dialogSave.setVisible(false);
											dialogSave.hide();
											if (fr !=null)
												fr.setVisible(true);
										}
									});
								}
							});
						}
					});	
				}
				else
				{
					frameNameSave.addStyleName("error");
				}
			}
		});
		//ajout de l'event sur le bouton annuler
		delSave.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				//dialogSave.setVisible(false);
				dialogSave.hide();
				if (fr !=null)
					fr.setVisible(true);
			}
		});
		visibilitySave.addItem("Tous", "0");
		visibilitySave.addItem("Perso","1");
		vpSave.add(new HTML("Nom du fichier"));	
		vpSave.add(frameNameSave);
		vpSave.add(new HTML("Partage"));
		vpSave.add(visibilitySave);
		vpSave.add(validSave);
		vpSave.add(delSave);
		dialogSave.add(vpSave);		
	}
	
	/**
	 * Fonction de création de la menuBar
	 */
	public void createMenuBar()
	{
        //création du menu pour chgt de fonction
        menu = new MenuBar(false);
        menu.setAutoOpen(false);
        menu.setWidth("100%");
        menu.setAnimationEnabled(true);
        
        
        //Commande executé par le menu Template
        cmdTempl = new Command()
		{
			public void execute()
			{
				centrPanel.clear();
				createListe();
				//TODO
				centrPanel.add(scrollPan);
			}
		};
		 //Commande executé par le menu Crea
		cmdCrea = new Command()
		{
			public void execute()
			{	
				centrPanel.clear();
				centrPanel.add(creaPanel);
			}
		};
		 //Commande executé par le menu Visu
		cmdVisu = new Command()
		{
			public void execute()
			{
				centrPanel.clear();
				visuPanel.clear();

				String build="<br/>";
				if (!buildString().equals(""))
					build=buildString();
				templatesFunc.toPdf("temp", build,new Long("0"), s.get("teacher_login"),  new AsyncCallback<String>()
				{
					public void onFailure(Throwable caught)
					{
							Window.alert("Export : "+SERVER_ERROR);
					}

					public void onSuccess(final String result)
					{
						//Ajout d'un timer pour attendre la création complete du pdf (du a l'utilisation du lib exterieure)
						Timer timer = new Timer()
						{
							public void run()
							{
								fr=new Frame("../Documents/"+result);
								fr.setSize(Window.getClientWidth()*16/20*9/10+"px",Window.getClientHeight()*15/20+"px");
								visuPanel.add(fr);
								centrPanel.add(visuPanel);
								
							}
						};
						timer.schedule(1000);	
					}
				});		
			}
		};
		 //Commande executé par le menu save
		cmdSave = new Command()
		{
			public void execute()
			{
				save();
			}
		};
		 //Commande executé par le menu export
		cmd2pdf = new Command()
		{
			public void execute()
			{
				export();
			}
		};
        
        menuTemplate = menu.addItem("Mes modèles", cmdTempl);
        menuCrea = menu.addItem("Creation", cmdCrea);
        menuVisu = menu.addItem("Visualisation", cmdVisu);
        menuVisu.setVisible(false);
        menuSave = menu.addItem("Sauvegarder",cmdSave);
        	menuSave.setVisible(false);
        menuExport = menu.addItem("Exporter pdf", cmd2pdf);
        	menuExport.setVisible(false);
	}
		
	/**
	 * Fonction qui transforme les balises en informations personnelles
	 * @return String adaptée
	 */
	public String buildString()
	{
			
		String code = textHtml.getHTML();

		if (code.contains("$monNom$"))
			code=code.replace("$monNom$", myValue.get("teacher_name")[0]+"");		
		
		if (code.contains("$monPrenom$"))
			code=code.replace("$monPrenom$", myValue.get("teacher_firstname")[0]+"");	

		if (code.contains("$monEmail$"))
			code=code.replace("$monEmail$", myValue.get("teacher_email")[0]+"");	
		
		if (code.contains("$monTel$"))
			code=code.replace("$monTel$", myValue.get("teacher_grainofsalt")[0]+"");
		
		if (code.contains("$dateJour$"))
			code=code.replace("$dateJour$", DateTimeFormat.getFormat("dd/MM/yyyy").format(new Date()));
		
		if (code.contains("$nomJour$"))
			code=code.replace("$nomJour$", convertFrench(DateTimeFormat.getFormat("EEEE").format(new Date())) );
		

		return code;
	}
	
	/**
	 * Fonction permetant l'exportation en pdf du code html présent (asynchrone)
	 */
	public void export()
	{
		//Initialisation de la boite de dialog d'exports
		initDialogExp();
		vpExp.clear();
		
		if (fr !=null)
			fr.setVisible(false);
		

		dialogExp.setGlassEnabled(true);
		dialogExp.setAnimationEnabled(true);
		dialogExp.setPopupPosition(600, 250);
		dialogExp.show();
		
		//ajout de l'event sur le bouton valid de la popup
		validExp.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
							
				if (!frameNameExp.getText().equals(""))
				{
					final Date d = new Date();
			
					templatesFunc.toPdf(frameNameExp.getText(), buildString(),d.getTime(), s.get("teacher_login"),  new AsyncCallback<String>()
					{
						public void onFailure(Throwable caught)
						{
							Window.alert("Export : "+SERVER_ERROR);	
						}
	
						public void onSuccess(String result)
						{
							String r="insert into document(document_name,document_path,document_date,document_visibility,document_subject) " +
									"values ('"+frameNameExp.getText()+"','"+result+"','"+d.getTime()+"','"+visibilityExp.getValue((visibilityExp.getSelectedIndex()))+"','"+courseExp.getValue(courseExp.getSelectedIndex())+"')";
						
							dataService.insert(r, new AsyncCallback<Integer>()
							{
								public void onFailure(Throwable caught)
								{	
									Window.alert("Data insert : "+SERVER_ERROR);
								}
	
								public void onSuccess(Integer resulta)
								{
									String r= "insert into teacher_document values ('"+resulta+"','"+s.get("teacher_login")+"')";
						
									dataService.insert(r, new AsyncCallback<Integer>()
									{
										public void onFailure(Throwable caught)
										{
											Window.alert("Data insert : "+SERVER_ERROR);
										}
	
										public void onSuccess(Integer result)
										{
											dialogExp.clear();
											//dialogExp.setVisible(false);
											dialogExp.hide();
											if (fr !=null)
													fr.setVisible(true);
										}
									});
								}
							});
						}
					});
				}
				else
				{
					frameNameExp.setStyleName("error");
				}
			}
		});
		
		//ajout de l'event sur le bouton annuler de la popup
		delExp.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				dialogExp.setVisible(false);
				dialogExp.hide();
				if (fr !=null)
					fr.setVisible(true);
			}
		});
		
		String r = "select * from subject";
	
		//Affichage de toutes les matières afin de sauvegarder le pdf pour une filiere donnée
		dataService.select(r,new AsyncCallback<HashMap<String,String[]>>()
		{
			public void onFailure(Throwable caught)
			{
				Window.alert("Liste matière : "+SERVER_ERROR);				
			}

			public void onSuccess(HashMap<String, String[]> result)
			{
				for (int i =0;i<result.get("subject_id").length;i++)
					courseExp.addItem(result.get("subject_name")[i],result.get("subject_id")[i] );
				
				visibilityExp.addItem("Tous", "0");
				visibilityExp.addItem("Perso","1");
				vpExp.add(new HTML("Nom du fichier"));	
				vpExp.add(frameNameExp);
				vpExp.add(new HTML("Partage"));
				vpExp.add(visibilityExp);
				vpExp.add(new HTML("Matière"));
				vpExp.add(courseExp);
				VerticalPanel vpButton = new VerticalPanel();
				vpButton.add(validExp);
				vpButton.add(delExp);
				
				vpExp.add(vpButton);
				dialogExp.add(vpExp);
			}
		});
	}

	/**
	 * Fonction de création de la boite de dialog de sauvegarde
	 */
	public void initDialogSave()
	{
		//CONSTRUCTION BOITE DIALOG SAVE
		dialogSave = new DialogBox();
		//dialogSave.setVisible(false);
		vpSave = new VerticalPanel();
			vpSave.setHorizontalAlignment(ALIGN_CENTER);
		validSave = new PushButton("Sauvegarder");
			validSave.setWidth("100px");
		delSave = new PushButton("Annuler");
			delSave.setWidth("100px");
		frameNameSave = new ValidTextBox();
		visibilitySave = new ListBox();
	}
	
	/**
	 * Fonction de création de la boite de dialog d'export
	 */
	public void initDialogExp()
	{
		//CONSTRUCTION BOITE DIALOG EXPORT
		dialogExp = new DialogBox();
		//dialogExp.setVisible(false);
		vpExp = new VerticalPanel();
			vpExp.setHorizontalAlignment(ALIGN_CENTER);
		validExp = new PushButton("Sauvegarder");
			validExp.setWidth("100px");
		delExp = new PushButton("Annuler");
			delExp.setWidth("100px");
		frameNameExp = new ValidTextBox();
		visibilityExp = new ListBox();
		courseExp = new ListBox();
		
	}
	
	/**
	 * Fonction d'initialisation du stackpanel d'insertion des balises
	 */
	public void initStackPanel()
	{
		func=new DecoratedStackPanel();
		func.setSize(Window.getClientWidth()*16/20*1/5+"px", Window.getClientHeight()*9/10*4/5+"px");
		treePerso = new Tree();
		treePerso.addItem("Mon Nom");
		treePerso.addItem("Mon Prénom");
		treePerso.addItem("Mon Email");
		treePerso.addItem("Mon Téléphone");
		
		treePerso.addSelectionHandler(new SelectionHandler<TreeItem>()
		{
			public void onSelection(SelectionEvent<TreeItem> event)
			{
				if (event.getSelectedItem().getText().equals("Mon Nom"))
					insertCommand("$monNom$");
				else if (event.getSelectedItem().getText().equals("Mon Prénom"))
						insertCommand("$monPrenom$");
					  else if (event.getSelectedItem().getText().equals("Mon Email"))
							insertCommand("$monEmail$");
						else if (event.getSelectedItem().getText().equals("Mon Téléphone"))
								insertCommand("$monTel$");
			}			
		});
		
		treeGen = new Tree();
		treeGen.addItem("Date du jour");
		treeGen.addItem("Nom du jour");
		
		
		treeGen.addSelectionHandler(new SelectionHandler<TreeItem>()
				{
					public void onSelection(SelectionEvent<TreeItem> event)
					{
						if (event.getSelectedItem().getText().equals("Date du jour"))
							insertCommand("$dateJour$");
						else if (event.getSelectedItem().getText().equals("Nom du jour"))
								insertCommand("$nomJour$");
							 
					}			
				});
		
		func.add(treePerso, "Personel", true);
		func.add(treeGen, "Général", true);
		
	}
	
	
	public void insertCommand(String s)
	{
		/*JsArrayString tx = RichTextToolbar.getSelection(textHtml.getElement());
		Integer startpos = Integer.parseInt(tx.get(1));
		//String selectedText = tx.get(0);
		String toFind = textHtml.getText().substring(0,startpos);
		String codeHtml = textHtml.getHTML();
		int newStartPos = codeHtml.indexOf(toFind)+toFind.length();
		textHtml.setHTML(codeHtml.substring(0, newStartPos)+s+codeHtml.substring(newStartPos,codeHtml.length()));
		 */
		Window.alert("Veuillez insérer la balise "+s+" à l'endroit désiré");
	}
	
	/**
	 * Fonction de création du richtextarea et de la richtexttoolbar
	 */
	public void initRichText()
	{
		insideCreaPanel = new VerticalPanel();
		
		textHtml = new RichTextArea();
		textHtml.setSize(Window.getClientWidth()*16/20*3/4+"px", Window.getClientHeight()*9/10*15/20+"px");
		
		toolbar = new RichTextToolbar(textHtml);
		textHtml.setWidth(Window.getClientWidth()*16/20*3/4+"px");
		
		textHtml.ensureDebugId("RichText");
		insideCreaPanel.add(toolbar);
		insideCreaPanel.add(textHtml);
		textHtml.addKeyUpHandler(new KeyUpHandler()
		{
			public void onKeyUp(KeyUpEvent event)
			{
				if (!textHtml.getText().equals(""))
				{
					menuSave.setVisible(true);
					menuExport.setVisible(true);
					menuVisu.setVisible(true);
				}
				else
				{
					menuVisu.setVisible(false);
					menuSave.setVisible(false);
					menuExport.setVisible(false);
				}
			}
		});	
	}
	
	/**
	 * Fonction de conversion d'un nom de jour anglais en francais
	 * @param jour en anglais
	 * @return jour en francais
	 */
	public String convertFrench(String sDay)
	{
		if (sDay.equals("Monday"))
			return "Lundi";
		else if (sDay.equals("Tuesday"))
				return "Mardi";
			else if (sDay.equals("Wednesday"))
				return "Mercredi";
				else if (sDay.equals("Thursday"))
					return "Jeudi";
					else if (sDay.equals("Friday"))
						return "Vendredi";
					else if (sDay.equals("Saturday"))
						return "Samedi";
					else if (sDay.equals("Sunday"))
						return "Dimanche";
		return sDay;
		
	}
	
	/**
	 * Fonction permettant le redimensionnement de l'ensemble des elements
	 */
	public void onResize()
	{
		 scrollPan.setSize(Window.getClientWidth()*16/20*19/20+"px",Window.getClientHeight()*9/10*17/20+"px");
		 flexTable.setWidth(Window.getClientWidth()*16/20*9/10+"px");
		 textHtml.setSize(Window.getClientWidth()*16/20*3/4+"px", Window.getClientHeight()*9/10*15/20+"px");
		 func.setSize(Window.getClientWidth()*16/20*1/5+"px", Window.getClientHeight()*9/10*4/5+"px");
		 fr.setSize(Window.getClientWidth()*16/20*9/10+"px",Window.getClientHeight()*15/20+"px");
			
	}
}